#!/usr/bin/python
'''
Use with output of fasta_flank_sam.py
Given an id, prints fasta alignments by strand.
'''
import sys

# parameters.
seq_id = sys.argv[1]
flank_file = sys.argv[2]
out_base = sys.argv[3]

# read in flank file.
fin = open(flank_file, "rb")
lines = fin.readlines()
fin.close()

# pull out all seqs matching.
res = {}
for line in lines:
	# tokenize.
	tmp = line.strip().split()
	id = tmp[0]
	seq = tmp[1]
	fseq = tmp[2]
	if id != seq_id: continue
	
	# add to dict,
	if seq not in res:
		res[seq] = []
	res[seq].append(fseq)
	
# make files.
i = 0
for seq in res:
	# open output.
	fname = "%s_%i.fasta" % (out_base, i)
	fout = open(fname, "wb")
	
	# write ref.
	fout.write(">ref_%i\n%s\n" % (i, seq))
	
	# write the rest.
	j = 0
	for fseq in res[seq]:
		fout.write(">seq_%i_%i\n%s\n" % (i, j, fseq))
		j += 1
		
	# incrememnt i.
	i += 1
	fout.close()

